<?php
header("Access-Control-Allow-Origin:*");

/**
 * 服务机构信息
 * @param unknown_type $pars
 * @throws Exception
 */
function serviceinfo($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();

		$store_id=empty($pars->store_id)?0:intval($pars->store_id);
		if(empty($store_id)){
			throw new Exception('服务机构不存在');
		}

		$sql="select state,service,service_reason,store_id,store_name,owner_name,region_name,address,tel,commentstar,comments,pricedescription,lat,lng,officestart,officeend,store_banner from cw_store s
where store_id=$store_id";
		$list=$db->getRow($sql);
		if(empty($list)){
			throw new Exception('服务机构不存在');
		}
		$i=intval($list['officestart']);
		$list['officestart']=str_pad(intval($i/60),2,'0',STR_PAD_LEFT).':'.str_pad(($i%60),2,'0',STR_PAD_LEFT);
		$i=intval($list['officeend']);
		$list['officeend']=str_pad(intval($i/60),2,'0',STR_PAD_LEFT).':'.str_pad(($i%60),2,'0',STR_PAD_LEFT);
		if($list['service']!=1){
			throw new Exception('服务机构:'.$list['service_reason']." 已关闭");
		}

		//优惠券
		$sql="SELECT coupon_id,coupon_name from cw_coupon where store_id=$store_id and if_issue=1 and start_time<=".gmtime()." and end_time>=".gmtime();
		$list['coupon']=$db->getAll($sql);
		
		//评论
		$sql="SELECT * from cw_storecomment where store_id=$store_id and if_show=1 order by add_time desc limit 10";
		$storecomment=$db->getAll($sql);
		foreach ($storecomment as $key=>$val){
			$val['add_time']=local_date('Y-m-d H:i:s',$val['add_time']);
			$list['comment'][]=$val;
		}
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 服务机构说明信息
 * @param unknown_type $pars
 * @throws Exception
 */
function servicedescription($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();

		$store_id=empty($pars->store_id)?0:intval($pars->store_id);
		if(empty($store_id)){
			throw new Exception('服务机构不存在');
		}

		$sql="select service,description,officestart,officeend,environment from cw_store s
where store_id=$store_id";
		$list=$db->getRow($sql);
		if(empty($list)){
			throw new Exception('服务机构不存在');
		}
	
		$i=intval($list['officestart']);
		$list['officestart']=str_pad(intval($i/60),2,'0',STR_PAD_LEFT).':'.str_pad(($i%60),2,'0',STR_PAD_LEFT);
		$i=intval($list['officeend']);
		$list['officeend']=str_pad(intval($i/60),2,'0',STR_PAD_LEFT).':'.str_pad(($i%60),2,'0',STR_PAD_LEFT);
		if($list['service']!=1){
			throw new Exception('服务机构因:'.$list['service_reason']." 已关闭");
		}

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 服务机构评论
 * @param unknown_type $pars
 */
function storecomment($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();
		if(empty($pars->uid)){
			throw new Exception('当前人员不存在');
		}
		$store_id=empty($pars->store_id)?0:intval($pars->store_id);
		$user_name=empty($pars->userself)||empty($pars->userself['real_name'])?'宠友':$pars->userself['real_name'];
		$star=empty($pars->star)?'':$pars->star;
		$content=empty($pars->content)?'':$pars->content;
		$pic=empty($pars->pic)?'':$pars->pic;
		$headimg=empty($pars->userself)?'':$pars->userself['headimgurl'];
		//默认显示
		$if_show=1;
		if(empty($store_id)){
			throw new Exception('服务机构不存在');
		}

		$storecomment = array('store_id'=>$store_id,
			'user_id'=>$pars->uid,
			'user_name'=>$user_name,
			'star'	=>$star,
			'content'=>$content,
			'add_time'=>gmtime(),
			'pic'	=>$pic,
			'headimg'=>$headimg,
			'if_show'=>$if_show,
		);
		$storecomment_mod =& m('storecomment');
		$comment_id=$storecomment_mod->add($storecomment);
		if(empty($comment_id)){
			throw new Exception('评论失败');
		}
		$oldnum=0;
		$oldstar=5;
		$sql="select count(1) as num,sum(star) as star from cw_storecomment where store_id=$store_id and if_show=1";
		$commentcount=$db->getRow($sql);
		if(!empty($commentcount)){
			$oldnum = intval($commentcount['num']);
			$oldstar = floatval($commentcount['star']);
		}
		$oldnum=$oldnum+1;
		$oldstar=$oldstar+$star;
		$commentstar = $oldstar/$oldnum;
		$sql="update cw_store set comments=comments+1,commentstar=$commentstar where store_id=$store_id";
		$db->query($sql);
		
		$list=array('comment_id'=>$comment_id);

		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 服务机构评论列表
 * @param unknown_type $pars
 * @throws Exception
 */
function storecommentlist($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();
		$uid=empty($pars->uid)?0:intval($pars->uid);
		if(empty($uid)){
			throw new Exception('当前人员不存在');
		}

		$store_id=empty($pars->store_id)?0:intval($pars->store_id);
		if(empty($store_id)){
			throw new Exception('服务机构不存在');
		}
		
		$row=empty($pars->row)?0:$pars->row;
		$size=empty($pars->size)?10:$pars->size;
	
		//评论
		$sql="SELECT * from cw_storecomment where store_id=$store_id and if_show=1 order by add_time desc limit $row,$size";
		$storecomment=$db->getAll($sql);
		foreach ($storecomment as $key=>$val){
			$val['add_time']=local_date('Y-m-d H:i:s',$val['add_time']);
			$list[]=$val;
		}
		
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 优惠券详情
 * @param unknown_type $pars
 * @throws Exception
 */
function storecoupon($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();
		$uid=empty($pars->uid)?0:intval($pars->uid);
		if(empty($uid)){
			throw new Exception('当前人员不存在');
		}

		$store_id=empty($pars->store_id)?0:intval($pars->store_id);
		if(empty($store_id)){
			throw new Exception('服务机构不存在');
		}
	
		$couponid = empty($pars->couponid)?0:intval($pars->couponid);
		if(empty($couponid)){
			throw new Exception('优惠券不存在');
		}
		//优惠券
		$sql="SELECT * from cw_coupon where store_id=$store_id and coupon_id=$couponid and if_issue=1 and start_time<=".gmtime()." and end_time>=".gmtime();
		$list=$db->getRow($sql);
	
		if(empty($list)){
			throw new Exception('优惠券不存在');
		}
		$list['start_time']=local_date('Y-m-d H:i:s',$list['start_time']);
		$list['end_time']=local_date('Y-m-d H:i:s',$list['end_time']);
		
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 优惠券领用
 * @param unknown_type $pars
 * @throws Exception
 */
function storecouponget($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();
		$uid=empty($pars->uid)?0:intval($pars->uid);
		if(empty($uid)){
			throw new Exception('当前人员不存在');
		}

		$store_id=empty($pars->store_id)?0:intval($pars->store_id);
		if(empty($store_id)){
			throw new Exception('服务机构不存在');
		}
	
		$couponid = empty($pars->couponid)?0:intval($pars->couponid);
		if(empty($couponid)){
			throw new Exception('优惠券不存在');
		}
		//优惠券
		$sql="SELECT * from cw_coupon where store_id=$store_id and coupon_id=$couponid and if_issue=1 and start_time<=".gmtime()." and end_time>=".gmtime();
		$list=$db->getOne($sql);
	
		if(empty($list)){
			throw new Exception('优惠券不存在');
		}
		
        $_user_mod =& m('member');
        $arr = generate(1, $couponid,$store_id);
        $i = 0;
        $_user_mod->createRelation('bind_couponsn', $uid, array($arr[$i]['coupon_sn'] => array('coupon_sn' =>$arr[$i]['coupon_sn'])));
        $list = array('coupon_sn'=>$arr[$i]['coupon_sn']);
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

    function generate($num, $id,$store_id)
    {
    	$_coupon_mod =& m('coupon');
        $use_times = $_coupon_mod->get(array('fields' => 'use_times', 'conditions' => 'store_id = ' . $store_id . ' AND coupon_id = ' . $id));

        if ($num > 1000)
        {
            $num = 1000;
        }
        if ($num < 1)
        {
            $num = 1;
        }
        $times = $use_times['use_times'];
        $add_data = array();
        $str = '';
        $pix = 0;
        if (file_exists(ROOT_PATH . '/data/generate.txt'))
        {
            $s = file_get_contents(ROOT_PATH . '/data/generate.txt');
            $pix = intval($s);
        }
        $max = $pix + $num;
        file_put_contents(ROOT_PATH . '/data/generate.txt', $max);
        $couponsn = '';
        $tmp = '';
        $cpm = '';
        $str = '';
        for ($i = $pix + 1; $i <= $max; $i++ )
        {
            $cpm = sprintf("%08d", $i);
            $tmp = mt_rand(1000, 9999);
            $couponsn = $cpm . $tmp;
            $str .= "('{$couponsn}', {$id}, {$times},".gmtime()."),";
            $add_data[] = array(
                'coupon_sn' => $couponsn,
                'coupon_id' => $id,
                'remain_times' => $times,
                );
        }
        $string = substr($str,0, strrpos($str, ','));
        $_coupon_mod->db->query("INSERT INTO cw_coupon_sn (coupon_sn, coupon_id, remain_times,get_time) VALUES {$string}", 'SILENT');
        return $add_data;
    }

/**
 * 我的优惠券
 * @param unknown_type $pars
 * @throws Exception
 */
function storecouponmy($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();
		$uid=empty($pars->uid)?0:intval($pars->uid);
		if(empty($uid)){
			throw new Exception('当前人员不存在');
		}
		$store_id=empty($pars->store_id)?0:intval($pars->store_id);
		$where="";
		if($store_id>0){
			$where=" and (store.store_id=$store_id or store.store_id=1)";
		}
		$row=empty($pars->row)?0:$pars->row;
		$size=empty($pars->size)?10:$pars->size;
		
		//优惠券
		$sql="SELECT c.*,s.coupon_sn,store.store_name,s.remain_times,s.use_time,s.get_time from cw_coupon c
		inner join cw_coupon_sn s on c.coupon_id=s.coupon_id
		inner join cw_user_coupon u on u.coupon_sn=s.coupon_sn
		inner join cw_store store on store.store_id=c.store_id ".$where." 
		where user_id=$uid order by get_time desc limit $row,$size";
		$list=$db->getAll($sql);
		
		foreach ($list as $key=>$val){
			$list[$key]['start_time']=local_date('Y-m-d H:i:s',$val['start_time']);
			$list[$key]['end_time']=local_date('Y-m-d H:i:s',$val['end_time']);
			$list[$key]['use_time']=local_date('Y-m-d H:i:s',$val['use_time']);
			$list[$key]['get_time']=local_date('Y-m-d H:i:s',$val['get_time']);
		}
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}

/**
 * 优惠券使用
 * @param unknown_type $pars
 * @throws Exception
 */
function storecouponuse($pars){
	$status=0;
	try{
		$db=&db();
		$list=array();
		$uid=empty($pars->uid)?0:intval($pars->uid);
		if(empty($uid)){
			throw new Exception('当前人员不存在');
		}

		$barcode=empty($pars->barcode)?'':$pars->barcode;
		if(empty($barcode)){
			throw new Exception('扫描错误');
		}
		$barcode_arr = explode('+',$barcode);
		$coupon_sn=empty($barcode_arr[0])?'':$barcode_arr[0];
		if(empty($coupon_sn)){
			throw new Exception('优惠券不存在');
		}
		$coupon_user=empty($barcode_arr[1])?0:intval($barcode_arr[1]);
		if(empty($coupon_sn)){
			throw new Exception('扫描用户错误');
		}
		$couponid = empty($barcode_arr[2])?0:intval($barcode_arr[2]);
		if(empty($couponid)){
			throw new Exception('扫描优惠券错误');
		}
		//优惠券
		$sql="SELECT * from cw_coupon where store_id=$uid and coupon_id=$couponid and if_issue=1 and start_time<=".gmtime()." and end_time>=".gmtime();
		$list=$db->getRow($sql);
	
		if(empty($list)){
			throw new Exception('优惠券已经过期');
		}
		
		//优惠券SN
		$sql="SELECT * from cw_coupon_sn s inner join cw_user_coupon u on u.coupon_sn=s.coupon_sn where u.user_id=$coupon_user and s.coupon_sn='$coupon_sn' and s.coupon_id=$couponid and s.remain_times>0";
		$list=$db->getRow($sql);
		if(empty($list)){
			throw new Exception('无效优惠券');
		}
		
		$sql="update cw_coupon_sn set remain_times=remain_times-1,use_time=".gmtime()." where coupon_sn='$coupon_sn'";
		$db->query($sql);
		$list=array('coupon_sn'=>$coupon_sn);
		$status=1;
	}
	catch (Exception $exp){
		$list=$exp->getMessage();
	}
	return JSONResult($status,$list,$pars);
}
?>